`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    16:09:29 04/03/2014 
// Design Name: 
// Module Name:    background 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module background(scroll_en,blank,hcount,vcount,HS,clk,rst,bg_block,bg_tile);

	input clk,rst,HS,scroll_en,blank;
	input [10:0] hcount,vcount;
	output [7:0] bg_tile;
	output	bg_block;

	parameter 	leftEdge = 32;//64;

	reg [3:0]	xIndex,yIndex;
	reg [4:0]	tileCount,line;
	reg [15:0] tile_addr;
	//reg	tile_sel;

	reg [17:0] delay;
	reg [4:0] offset;

	grass backdrop(
		.clka(clk), // input clka
		.wea(1'b0), // input [0 : 0] wea
		.addra((32*(line-offset))+tileCount), // input [15 : 0] addra
		.dina(8'd0), // input [7 : 0] dina
		.douta(bg_tile) // output [7 : 0] dout
	);
	
	initial begin
		tileCount =0;
		line =0;
		xIndex = 0;
		yIndex = 0;
	end

	/* Routine for game board scrolling */

	always @ (posedge clk) begin
		if (rst) delay <= 0;
		else if(!HS)delay <= delay + 1'b1;
	end

	always @ (posedge clk) begin
		if (rst || ~scroll_en) offset <= 0;
		else if (delay == 5000 && offset <31 && scroll_en) offset <= offset + 1'b1;
		else if (offset == 31) offset <= 0;
	end
		
	/* Routine for populating background block */

	always @ (posedge clk) begin
		if(rst)	tileCount <= 5'd0;
		else if (bg_block) begin
			if (tileCount < 31) tileCount <= tileCount + 1'b1;
			else	tileCount <= 5'd0;
		end
	end

	always @ (posedge clk) begin
		if(rst)	xIndex <= 4'd0;	// might need 4'hFF
		else if (bg_block) begin 
			if(tileCount == 31) begin
				if (xIndex == 13) xIndex <= 5'd0;
				else xIndex <= xIndex + 1'b1;
			end
		end
	end

	always @ (posedge clk) begin
		if(rst)	line <= 0;
		else if (bg_block) begin
			if(xIndex == 13 && tileCount == 31) begin
				if (line == 31) line <= 0;
				else line <= line + 1'b1;
			end
		end
	end

	always @ (posedge clk) begin
		if(rst)	yIndex <= 4'd0;	// might need 4'hFF
		else if (bg_block) begin
			if(line == 31 && xIndex == 13 && tileCount == 31) begin
				if (yIndex == 13  ) yIndex <= 5'd0;
				else yIndex <= yIndex + 1'b1;
			end
		end
	end

	/* game board */
	assign bg_block = ~blank & (	hcount >= leftEdge & hcount <= leftEdge + (32*14)-1
							&	vcount >= 32 & vcount <= (32*14)-1);

endmodule
